const { v4: uuidv4 } = require("uuid");

// 在 ctx 实例中添加自定义方法，规范返回数据的格式
module.exports = {
  success(msg = "交易成功", data = null) {
    const isObj = typeof msg === "object";
    isObj && (data = msg);
    return {
      errno: 0,
      message: isObj ? "交易成功" : msg,
      data: data,
    };
  },
  list(msg = "交易成功", data = null) {
    const isObj = typeof msg === "object";
    isObj && (data = msg);
    return {
      errno: 0,
      message: isObj ? "交易成功" : msg,
      ...data,
    };
  },
  fail(message = "交易失败", data = null) {
    const isObj = typeof message === "object";
    isObj && (data = message);
    return {
      errno: 1,
      message: isObj ? "交易失败" : message,
      data: data,
    };
  },
  uuid() {
    return uuidv4().replace("-", "").substr(0, 12);
  },
  cTime() {
    // 返回当前的时间
    return new Date();
  },
  /**
   * 处理sql语句的模糊查询条件语句
   * @return {
   *  str:string  sql语句
   *  has:boolean 是否需要增加条件
   * }
   * @params object
   */
  condition(params) {
    const obj = { ...params };
    delete obj.pagesize;
    delete obj.pagenum;
    delete obj.total;

    let exclude = ['catename', 'catevalue', 'cateid', 'book_cate_name', 'book_cate_value']
    let hasCondition = false;
    let condition = "";
    for (var key in obj) {
      if (obj[key]) {
        hasCondition = true;
        if (exclude.includes(key)){
          condition += `${key} = '${obj[key]}' and `;
        }else {
          condition += `${key} like '%${obj[key]}%' and `;
        }
      }
    }
    condition = condition.substring(0, condition.length - 4);
    return {
        str: condition,
        has: hasCondition
    }
  }
};
